/**
 * binary转16进制字符串
 * @param s
 * @returns {string}
 */
function bin2hex(s) {
  let i;
  let l;
  let o = '';
  let n;
  s += '';
  for (i = 0, l = s.length; i < l; i++) {
    n = s.charCodeAt(i).toString(16);
    o += n.length < 2 ? '0' + n : n; // 10位一下补0
  }
  return o;
}

/**
 * Canvas指纹
 * https://en.wikipedia.org/wiki/Canvas_fingerprinting
 * https://browserleaks.com/canvas#how-does-it-work
 * @param domain
 * @returns {string}
 */
export function deviceId(domain) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  // eslint-disable-next-line no-restricted-globals
  const txt = domain || location.host;
  ctx.textBaseline = 'top';
  // The most common type
  ctx.font = "14px 'Arial'";
  ctx.textBaseline = 'alphabetic';
  ctx.fillStyle = '#f60';
  ctx.fillRect(125, 1, 62, 20);
  // Some tricks for color mixing to increase the difference in rendering
  ctx.fillStyle = '#069';
  ctx.fillText(txt, 2, 15);
  ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
  ctx.fillText(txt, 4, 17);
  const b64 = canvas.toDataURL().replace('data:image/png;base64,', '');
  const bin = atob(b64); // ASCII to binary , decodes a base64 encoded string
  const crc = bin2hex(bin.slice(-20, -12)); // 获取图片 crc checksum 并转成16进制
  return crc;
}
